<template>
  <el-row :gutter="10">
    <el-col :span="7">
      <el-card class="content">
        <div slot="header">
          <div style="height: 32px;padding-top: 5px;font-size:16px">门类树标签</div>
        </div>
        <div class="left-tree" v-loading="leftLoading">
          <el-tree :data="leftData"
                   :props="leftProps"
                   default-expand-all
                   @node-click="handleLeftNodeClick">
          </el-tree>
        </div>
      </el-card>
    </el-col>

    <el-col :span="10">
      <el-card class="content">
        <div slot="header">
          <el-button size="small"
                     @click="addCatalogNode"
                     v-if="permission.md_categoryLabel_create">新增目录</el-button>
          <el-button size="small"
                     type="primary"
                     :loading="saveBtnLoading"
                     @click="handleSaveCategoryTree"
                     v-if="permission.md_categoryLabel_create">保存</el-button>
        </div>
        <div class="center-tree" v-loading="centerLoading">
          <el-tree
            :key="key"
            :data="centerData"
            :props="centerProps"
            empty-text="请选择左侧门类树标签"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            @node-click="handleCenterNodeClick"
            @node-drop="handleDrop"
            :draggable="permission.md_categoryLabel_create"
            :allow-drop="allowDrop"
          >
           <!-- default-expand-all-->
            <div class="hover-show1" slot-scope="{ node, data }" style="width: 100%">
              <i :class="data.icon" style="margin-right: 5px"></i>
              <span class="treeNodeLabel">{{ node.label }}</span>
              <span class="btn-box" v-if="permission.md_categoryLabel_create">
                <!--下-->
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-bottom"
                  style="font-size: 18px;float: right;margin-left: 5px"
                  @click.stop="() => downdown(data, centerData)">
                </el-button>
                <!--上-->
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-top"
                  style="font-size: 18px;float: right;margin-left: 5px"
                  @click.stop="() => upup(data, centerData)">
                </el-button>
                <!--删除-->
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-remove-outline"
                  style="font-size: 18px;float: right;margin-left: 5px"
                  @click.stop="() => removeNode(data, centerData)">
                </el-button>
                <!--编辑-->
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-edit"
                  style="font-size: 18px;float: right"
                  @click.stop="() => editNode(data, centerData)"
                >
                </el-button>
              </span>
            </div>
          </el-tree>
        </div>

      </el-card>
    </el-col>

    <el-col :span="7">
      <el-card class="content">
        <div slot="header">
          <div style="height: 32px;padding-top: 5px;font-size:16px">系统门类列表</div>
        </div>
        <div class="right-tree" v-loading="rightLoading">
          <el-tree
            :data="rightData"
            :props="rightProps"
            default-expand-all
            node-key="id">
            <div class="hover-show1" slot-scope="{ node, data }" style="width: 100%">
              <span>{{ node.label }}</span>
              <span class="btn-box" v-if="permission.md_categoryLabel_create">
                <!--添加-->
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-circle-plus-outline"
                  style="font-size: 18px;margin-left: 5px"
                  @click="() => addCategoryNode(node, data)">
                </el-button>
              </span>
            </div>
          </el-tree>
        </div>

      </el-card>
    </el-col>

    <!--编辑节点-->
    <el-dialog title="编辑节点"
               :destroy-on-close="true"
               :visible.sync="editNodeBox"
               :modal-append-to-body="false"
               append-to-body
               width="500px">
      <el-form :model="editNodeForm" :rules="editNodeFormRules" ref="editNodeForm">
        <el-form-item label="上级节点" label-width="80px" prop="pid">
          <avue-input-tree
            default-expand-all
            include-half-checked
            v-model="editNodeForm.pid"
            placeholder="请选择上级节点"
            type="tree"
            :dic="editNodeDic"
            :props="props"
          ></avue-input-tree>
        </el-form-item>
        <el-form-item label="节点名称" label-width="80px" prop="nodeName">
          <el-input v-model="editNodeForm.nodeName"></el-input>
        </el-form-item>
        <el-form-item label="节点图标" label-width="80px" prop="icon">
          <avue-input-icon v-model="editNodeForm.icon"
                           placeholder="请选择图标"
                           :icon-list="iconList">
          </avue-input-icon>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editNodeBox = false">取 消</el-button>
        <el-button type="primary" @click="certainEditCatalogNode">确 定</el-button>
      </div>
    </el-dialog>

  </el-row>
</template>

<script>

import {
  editCategoryTree,
  getCategoryAll,
  getCategoryLabelAll,
  getCategoryTree
} from '../../../../api/category/category'
import iconList from '../../../../config/iconList'

export default {
  name: 'ArchivesCategory', // 档案门类显示
  data () {
    return {
      key: 1,
      leftLoading: true,
      rightLoading: true,
      centerLoading: false,
      leftData: [],
      activeLabelCode: '',
      editNodeDic: [],
      newNodeId: 0,
      editNodeBox: false,
      saveBtnLoading: false,
      leftProps: {
        label: 'labelName'
      },
      centerProps: {
        label: 'nodeName'
      },
      rightProps: {
        label: 'categoryName'
      },
      centerData: [],
      rightData: [],
      editNodeForm: { id: '', pid: '', nodeName: '', icon: '' },
      editNodeFormRules: {
        nodeName: [{ required: true, message: '请输入目录名称' }]
      },
      props: {
        label: 'nodeName',
        value: 'id',
        children: 'children'
      },
      updateNode: {},
      permission: {
        md_categoryLabel_create: true
      },
      centerNodeId: '' // 中间选中节点id
    }
  },
  mounted () {
    this.getData()
  },
  computed: {
    iconList () {
      return iconList || []
    }
  },
  methods: {
    getData () {
      getCategoryLabelAll().then(res => {
        this.leftData = res.data.data
        this.leftLoading = false
      })
      getCategoryAll().then(res => {
        this.rightData = res.data.data
        this.rightLoading = false
      })
    },
    handleLeftNodeClick (data) {
      const labelCode = data.labelCode
      this.activeLabelCode = labelCode
      this.centerLoading = true
      getCategoryTree(labelCode, this.$route.query.isNotAjJnNode).then(res => {
        this.centerData = res.data.data
        this.centerLoading = false
      }).catch(() => {
        this.centerLoading = false
      })
    },
    handleSaveCategoryTree () { // 保存门类树
      this.saveBtnLoading = true
      const labelCode = this.activeLabelCode
      const nodes = this.centerData
      this.sorterTree(nodes)
      const categoryLabelNode = {
        labelCode,
        nodes
      }
      /* console.log(categoryLabelNode)
      this.saveBtnLoading = false */
      editCategoryTree(categoryLabelNode).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.centerLoading = true
        getCategoryTree(labelCode, this.$route.query.isNotAjJnNode).then(res => {
          this.centerData = res.data.data
          this.centerLoading = false
        }).catch(() => {
          this.centerLoading = false
        })
        this.saveBtnLoading = false
      }).catch(() => {
        this.saveBtnLoading = false
      })
    },
    sorterTree (data) {
      if (!data) {
        return
      }
      data.forEach((v, index) => {
        v.orderNo = index + 1
        delete v.id
        if (v.children && v.children.length > 0) {
          this.sorterTree(v.children)
        }
      })
    },
    addCatalogNode () { // 新增目录
      if (this.activeLabelCode === '') {
        this.$message({
          message: '请先选择门类标签!',
          type: 'warning'
        })
        return
      }
      const nodeId = 'newNode-' + this.newNodeId++
      const node = { nodeName: '新增目录', id: nodeId, orderNo: this.centerData.length, children: [] }
      this.centerData.push(node)
    },
    certainEditCatalogNode () {
      const pid = this.editNodeForm.pid
      const nodeName = this.editNodeForm.nodeName
      const icon = this.editNodeForm.icon
      const node = {
        nodeName,
        icon
      }
      this.nodeUpdatePid(pid, node, this.editNodeForm.id, this.centerData)
      this.editNodeBox = false
    },
    allowDrop (draggingNode, dropNode, type) {
      return !(dropNode.data.idCategory && dropNode.data.idCategory !== '')
    },
    handleDrop (draggingNode, dropNode, dropType, ev) { // 更新排序后节点的pid
      let pid = ''
      if (dropType === 'inner') {
        pid = dropNode.id
      } else {
        pid = dropNode.pid
      }
      const id = draggingNode.id
      this.nodeUpdatePid(pid, null, id, this.centerData)
    },
    nodeUpdatePid (pid, node, id, data) {
      if (!data) {
        return
      }
      data.forEach((v) => {
        if (id && v.id === id) {
          v.pid = pid
          if (typeof (node.nodeName) !== 'undefined') {
            v.nodeName = node.nodeName
          }
          if (typeof (node.icon) !== 'undefined') {
            v.icon = node.icon
          }
          return
        }

        if (v.children && v.children.length > 0) {
          this.nodeUpdatePid(pid, node, id, v.children)
        }
      })
    },
    addNode (data, node, pid) {
      if (!data) {
        return
      }
      data.forEach((v, index) => {
        if (v.id === pid) {
          if (!v.children) {
            v.children = []
          }
          v.children.push(node)
          return
        }
        if (v.children && v.children.length > 0) {
          this.addNode(data.children, node, pid)
        }
      })
    },
    editNode (data) { // 编辑节点
      this.updateNode = data
      this.editNodeBox = true
      this.editNodeForm = {
        id: data.id,
        pid: data.pid,
        nodeName: data.nodeName,
        icon: data.icon
      }
      getCategoryTree(this.activeLabelCode, this.$route.query.isNotAjJnNode).then(res => {
        this.editNodeDic = res.data.data
        this.removeLeaf(data.id, this.editNodeDic)
        this.editNodeForm.pid = data.pid
      })
    },
    upup (node, data) {
      if (!data) {
        return
      }
      for (let i = 0; i < data.length; i++) {
        const v = data[i]
        if (v.id === node.id) {
          if (i === 0) return
          data.splice(i, 1)
          data.splice(i - 1, 0, node)
          this.key++
          return
        }

        if (v.children && v.children.length > 0) {
          this.upup(node, v.children)
        }
      }
    },
    downdown (node, data) {
      if (!data) {
        return
      }
      for (let i = 0; i < data.length; i++) {
        const v = data[i]
        if (v.id === node.id) {
          if (i === data.length - 1) return
          data.splice(i, 1)
          data.splice(i + 1, 0, node)
          this.key--
          return
        }
        if (v.children && v.children.length > 0) {
          this.downdown(node, v.children)
        }
      }
    },
    removeNode (data, centerData) { // 删除节点
      if (data.children && data.children.length > 0) {
        this.$confirm('确定删除该节点及其子节点?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.removeNodeById(data.id, this.centerData)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.removeNodeById(data.id, this.centerData)
      }
    },
    removeNodeById (id, data) {
      if (!data) {
        return
      }
      data.forEach((v, index) => {
        if (v.id === id) {
          data.splice(index, 1)
          return
        }
        if (v.children && v.children.length > 0) {
          this.removeNodeById(id, v.children)
        }
      })
    },
    addCategoryNode (node, data) {
      if (this.activeLabelCode === '') {
        this.$message({
          message: '请先选择门类标签!',
          type: 'warning'
        })
        return
      }
      const id = 'newNode-' + this.newNodeId++
      const newNode = {
        id,
        pid: '0',
        idCategory: data.id,
        categoryType: data.categoryType,
        orderNo: this.centerData.length,
        nodeName: data.categoryName
        // is_show_ajjn_label: ''
      }
      if (this.centerNodeId) {
        // 添加到指定位置目录下面，目前只做了两级
        this.centerData.map(item => {
          if (item.id === this.centerNodeId) {
            if (item.children) {
              item.children.push(newNode)
            } else {
              this.centerData.push(newNode)
            }
          }
          if (item.children) {
            item.children.map(items => {
              if (items.id === this.centerNodeId) {
                items.children.push(newNode)
              }
            })
          }
        })
        return
      }
      this.centerData.push(newNode)
    },
    handleCenterNodeClick (data) {
      // 获取中间排序点击节点
      this.centerNodeId = data.id
    },
    removeLeaf (id, data) {
      if (!data) {
        return
      }
      for (let i = 0; i < data.length; i++) {
        if (!data) return
        const v = data[i]
        if (v.id === id || v.idCategory) {
          data.splice(i, 1)
          i--
        }
        if (v.children && v.children.length > 0) {
          this.removeLeaf(id, v.children)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-button+.el-button{
    margin-left: 5px;
  }
  .treeNodeLabel{
    font-size: 16px;
  }
  ::v-deep .el-tree-node__label {
    font-size: 16px !important;
  }
  .btn-box{
    display: none;
  }
  .hover-show1:hover {
    .btn-box{
      display: inline-flex;
    }
  }
  .content{
    height: calc(100vh - 80px);
    .left-tree, .right-tree, .center-tree{
      height: calc(100vh - 180px);
      overflow-y: auto;
    }
  }
</style>
